package com.free.file.controller;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.ftp.Ftp;
import com.free.common.core.constant.FileFtpConstants;
import com.free.common.core.pojo.FileInfo;
import com.free.common.core.utils.file.FileUtils;
import com.free.common.core.web.domain.R;
import com.free.file.service.ISysFileService;
import com.free.system.api.domain.SysFile;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 文件请求处理
 *
 * @author free
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload" )
    public R<SysFile> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败" , e);
            return R.fail(e.getMessage());
        }
    }

    @PostMapping("/delete" )
    public R<SysFile> delete(@RequestBody FileInfo fileInfo) {
        sysFileService.delete(fileInfo);
        return R.ok();
    }

    @GetMapping("/statics/uploadTmp/*" )
    public void uploadTmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("uploadTmp:进来了" );
        download(request, response);
    }

    @GetMapping("/statics/download/**" )
    public synchronized void download(HttpServletRequest request, HttpServletResponse response) throws
            IOException {
        log.info("进来下载了--{}" , request.getRequestURI());
        String ftpDownPrefix = FileFtpConstants.FTP_DOWN_PREFIX;
        String fileAbsPath = new String(URLDecoder.decode(request.getRequestURI().getBytes(StandardCharsets.UTF_8)));
        try (ServletOutputStream os = response.getOutputStream();
//             Ftp ftp = new Ftp("192.168.2.120", 21, "note", "yhl580230");) {
             Ftp ftp = new Ftp("192.168.2.120" );) {
            fileAbsPath = fileAbsPath.replace("/statics/download" , "" );
            String fileName = fileAbsPath.substring(fileAbsPath.lastIndexOf("/" ) + 1);
            String filePath = fileAbsPath.substring(0, fileAbsPath.lastIndexOf("/" ));
            System.out.println("下载文件的名称：" + fileAbsPath);
            // 1. 根据下载相对目录获取下载目录在服务器部署之后绝对目录
            // 3. 获取响应输出流
            response.setContentType("text/plain;charset=UTF-8" );
            // 4. 附件下载 attachment 附件 inline 在线打开(默认值)
            response.setHeader("content-disposition" , "attachment;fileName=" + URLEncodeUtil.encode(fileName));
            // 5. 处理下载流复制

            FTPFile[] ftpFiles = ftp.getClient().listFiles(filePath.replace("/statics/download" , "" ) + File.separator + fileName);
            if (ObjectUtil.isNotEmpty(ftpFiles)) {
                filePath = filePath.replace("/statics/download" , "" );
                long size = ftpFiles[0].getSize();
                response.setContentLength((int) size);
            } else {
                ftpFiles = ftp.getClient().listFiles(filePath.replace("/statics" , "" ) + File.separator + fileName);
                if (ObjectUtil.isNotEmpty(ftpFiles)) {
                    filePath = filePath.replace("/statics" , "" );
                    long size = ftpFiles[0].getSize();
                    response.setContentLength((int) size);
                } else {
                    ftpFiles = ftp.getClient().listFiles(filePath.replace("/statics" , "/Note/uploadTmp" ) + File.separator + fileName);
                    if (ObjectUtil.isNotEmpty(ftpFiles)) {
                        filePath = filePath.replace("/statics" , "/Note/uploadTmp" );
                        long size = ftpFiles[0].getSize();
                        response.setContentLength((int) size);
                    }
                }
            }


            ftp.download(filePath.replace("/statics/download" , "" ), fileName, os);
            // 释放资源
        } catch (Exception e) {
            e.printStackTrace();
            log.info("下载失败了--{}" , e.getMessage());
        }

    }

    @GetMapping("/statics/**" )
    public void statics(HttpServletRequest request, HttpServletResponse response) throws
            IOException {
        this.download(request, response);
    }
}
